package com.atguigu.gmall.realtime.app.func;

import com.alibaba.fastjson.JSONObject;
import com.atguigu.gmall.realtime.beans.DimJoinFunction;
import com.atguigu.gmall.realtime.common.GmallConfig;
import com.atguigu.gmall.realtime.utils.HbaseUtil;
import com.atguigu.gmall.realtime.utils.RedisUtil;
import io.lettuce.core.api.StatefulRedisConnection;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.functions.async.ResultFuture;
import org.apache.flink.streaming.api.functions.async.RichAsyncFunction;
import org.apache.hadoop.hbase.client.AsyncConnection;

import java.util.Collections;
import java.util.concurrent.CompletableFuture;
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.function.Supplier;

/**
 * @author Felix
 * @date 2023/11/21
 * 发送异步请求进行维度关联模板类
 */
public abstract class DimAsyncFunction<T> extends RichAsyncFunction<T, T> implements DimJoinFunction<T> {
    private StatefulRedisConnection<String, String> asyncRedisConn;
    private AsyncConnection asyncHbaseConn;
    private String tableName;

    public DimAsyncFunction(String tableName) {
        this.tableName = tableName;
    }

    @Override
    public void open(Configuration parameters) throws Exception {
        asyncRedisConn = RedisUtil.getAsyncRedisConnection();
        asyncHbaseConn = HbaseUtil.getAsyncHbaseConnection();
    }

    @Override
    public void close() throws Exception {
        RedisUtil.closeAsyncRedisConnection(asyncRedisConn);
        HbaseUtil.closeAsyncHbaseConnection(asyncHbaseConn);
    }

    @Override
    public void asyncInvoke(T obj, ResultFuture<T> resultFuture) throws Exception {
        //创建异步编排对象  执行异步任务（从Redis中查询维度数据），并将结果返回
        CompletableFuture.supplyAsync(
            new Supplier<JSONObject>() {
                @Override
                public JSONObject get() {
                    JSONObject dimJsonObj = RedisUtil.asyncGetDimInfo(asyncRedisConn, tableName + ":" + getKey(obj));
                    return dimJsonObj;
                }
            }
            //串行执行异步任务  有入参(上一个任务返回值)，有返回值
            // 判断是否缓存命中，如果没有命中，发送请求到Hbase中查询维度
        ).thenApplyAsync(
            new Function<JSONObject, JSONObject>() {
                @Override
                public JSONObject apply(JSONObject dimJsonObj) {
                    if (dimJsonObj == null) {
                        System.out.println("~~从Hbase中查询" + tableName + "表的" + getKey(obj) + "维度数据~~");
                        //没有命中缓存  发送请求到hbase中查询维度数据
                        dimJsonObj = HbaseUtil.getDimInfoFromHbaseByAsync(asyncHbaseConn, GmallConfig.HBASE_NAMESPACE,tableName,getKey(obj));
                        if(dimJsonObj != null){
                            //将查询出来的维度放到redis中缓存起来
                            RedisUtil.asyncWriteDim(asyncRedisConn,tableName+":"+getKey(obj),dimJsonObj);
                        }
                    } else {
                        System.out.println("~~从Redis中查询" + tableName + "表的" + getKey(obj) + "维度数据~~");
                    }
                    return dimJsonObj;
                }
            }
            //执行异步任务   有入参 无返回值
        ).thenAcceptAsync(
            new Consumer<JSONObject>() {
                @Override
                public void accept(JSONObject dimJsonObj) {
                    if(dimJsonObj != null){
                        //将维度对象的属性补充到流中的对象上
                        join(dimJsonObj,obj);
                        //将补充完维度属性的流中对象传递到下游
                        resultFuture.complete(Collections.singleton(obj));
                    }
                }
            }
        );
    }

    // 如果异步超时,会执行这个方法
    @Override
    public void timeout(T input, ResultFuture<T> resultFuture) throws Exception {
        // 根据自己情况进行处理
        throw new RuntimeException("异步超时:一般是其他原因导致的异步超时, 请检查: \n" +
            "1.检查集群是否都 ok: hdfs redis hbase kafka. \n" +
            "2.检查下 redis 的配置 bind 0.0.0.0 \n" +
            "3.检查用到的6张维度表是否都在,并且每张表都数据. 最好通过 maxwell-bootstrap 同步一下 \n" +
            "4. 找我" +
            "");
    }

}
